package cn.com.cfae.iras.doc.analyze.components.commonsense;

import cn.com.cfae.iras.doc.analyze.components.BaseComponent;
import cn.com.cfae.iras.doc.analyze.components.beans.ComponentResult;
import cn.com.cfae.iras.doc.analyze.components.consistency.U1004;
import cn.com.cfae.iras.doc.analyze.parse.kv.KVText;
import cn.com.cfae.iras.doc.analyze.parse.kv.TextLayout;
import cn.com.cfae.iras.doc.analyze.parse.model.ChapterModel;
import cn.com.cfae.iras.doc.analyze.parse.model.DocumentModel;
import cn.com.cfae.iras.doc.analyze.parse.model.ExtractBizModel;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zouxun on 2018/10/29
 */
@Component("C1003")
@Scope("prototype")
public class C1003 extends BaseComponent {
    private static Logger logger = LoggerFactory.getLogger(C1003.class);

    @Autowired
    U1004 u1004;
    @Autowired
    C1002 c1002;

    @Override
    public List<ComponentResult> handlerM() {
        logger.info("开始调用C1003组件，处理M表..............");
        List<ComponentResult> componentResults = ruleCheck();
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBM() {
        logger.info("开始调用C1003组件，处理BM表..............");
        List<ComponentResult> componentResults = ruleCheck();
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerDM() {
        logger.info("开始调用C1003组件，处理DM表..............");
        List<ComponentResult> componentResults = ruleCheck();
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBDM() {
        logger.info("开始调用C1003组件，处理BDM表..............");
        List<ComponentResult> componentResults = ruleCheck();
        return componentResults;
    }

    private Calendar dealDate(String text,Boolean flag){
        try{
            text=text.replaceAll("[\\s|【|】|\\[|\\]|(|)|（|）]{1,}","");
            logger.info("处理时间：{}",text);

            //解析文本，匹配年份
            String yearRegex = "(\\d{1,}年)*";
            Pattern pattern = Pattern.compile(yearRegex);
            Matcher matcher = pattern.matcher(text);
            List<String> yearList = new ArrayList<>();

            while(matcher.find()) {
                if(StringUtils.isNotEmpty(matcher.group())){
                    yearList.add(matcher.group().substring(0,matcher.group().indexOf("年")));
                }
            }
            logger.info("匹配年份：{}",yearList);

            //解析文本，匹配月份
            String monthRegex = "(\\d{1,}月)*";
            List<String> monthList = new ArrayList<>();
            pattern = Pattern.compile(monthRegex);
            matcher = pattern.matcher(text);
            while(matcher.find()) {
                if(StringUtils.isNotEmpty(matcher.group())){
                    monthList.add(matcher.group().substring(0,matcher.group().indexOf("月")));
                }
            }
            logger.info("匹配月份：{}",monthList);

            //解析文本，匹配日期
            String dayRegex = "(\\d{1,}日)*";
            List<String> dayList = new ArrayList<>();
            pattern = Pattern.compile(dayRegex);
            matcher = pattern.matcher(text);
            while(matcher.find()) {
                if(StringUtils.isNotEmpty(matcher.group())){
                    dayList.add(matcher.group().substring(0,matcher.group().indexOf("日")));
                }
            }
            logger.info("匹配日期：{}",dayList);

            if(monthList.size()>0 && dayList.size()>0){
                Calendar calendar = Calendar.getInstance();

                if(!flag){
                    if(yearList.size()>0){
                        String year=Collections.max(yearList);
                        logger.info("年：{}",year);

                        calendar.set(Calendar.YEAR,Integer.parseInt(year));
                    }
                }

                String month=Collections.max(monthList);
                logger.info("月：{}",month);
                String day=Collections.max(dayList);
                logger.info("日：{}",day);

                if(Integer.valueOf(month)<10){
                    month = month.replace("0","");
                }
                calendar.set(Calendar.MONTH,Integer.valueOf(month)-1);

                if(Integer.valueOf(day)<10){
                    day = day.replace("0","");
                }
                calendar.set(Calendar.DATE,Integer.valueOf(day));

                return calendar;
            }else{
                return null;
            }

        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    private List<ComponentResult> ruleCheck(){
        DocumentModel documentModel = super.getExtractData();

        List<ComponentResult> componentResults = new ArrayList<>();

        String keyword="付息日：XXXX年XX月XX日=起息日+发行期限，“时间计算时按照算头不算尾原则”，若是长期限品种则发行期限内，每年付息一次；短期限品种利息本金一次到期兑付。（如遇法定节假日，则顺延至下一工作日）即计算理论付息日";

        ComponentResult componentResult = u1004.getComponentResult(getCatalogId(),getChapterId(),getRuleTitle(),keyword,"",true,getRegulationId(),1,null,"03");

        ComponentResult qxrComponentResult = u1004.getComponentResult(getCatalogId(),getChapterId(),getRuleTitle(),getCatalogId().concat("起息日"),"",true,getRegulationId(),1,null,"03");

        ComponentResult fxqxComponentResult = u1004.getComponentResult(getCatalogId(),getChapterId(),getRuleTitle(),getCatalogId().concat("发行期限"),"",true,getRegulationId(),1,null,"03");

        try{
            ChapterModel chapterModel = documentModel.getChapterModel(getCatalogId());

            if(chapterModel!=null){
                componentResult.setPageNum(chapterModel.getStartPage());
                qxrComponentResult.setPageNum(chapterModel.getStartPage());
                fxqxComponentResult.setPageNum(chapterModel.getStartPage());

                //付息日
                KVText fxrKVTextValue=getKVTextValue(getCatalogId(),"FXTK","FXTKFXR");

                KVText fxrKVTextKey=getKVTextKey(getCatalogId(),"FXTK","FXTKFXR");

                //起息日
                KVText qxrKVTextValue=getKVTextValue(getCatalogId(),"FXTK","QXR");

                KVText qxrKVTextKey=getKVTextKey(getCatalogId(),"FXTK","QXR");

                //发行期限
                KVText fxqxKVTextValue=getKVTextValue(getCatalogId(),"FXTK","FXQX");

                KVText fxqxKVTextKey=getKVTextKey(getCatalogId(),"FXTK","FXQX");


                if(qxrKVTextValue!=null && fxqxKVTextValue!=null){
                    qxrComponentResult.setPageNum(qxrKVTextValue.getPageNumber());
                    fxqxComponentResult.setPageNum(fxqxKVTextValue.getPageNumber());

                    if(qxrKVTextKey!=null){
                        qxrComponentResult=c1002.setTextPosition(qxrKVTextKey,qxrComponentResult);
                    }

                    if(fxqxKVTextKey!=null){
                        fxqxComponentResult=c1002.setTextPosition(fxqxKVTextKey,fxqxComponentResult);
                    }

                    String qxrText = qxrKVTextValue.getText();
                    logger.info("抽取的起息日为：{}，页码为：{}",qxrText,qxrKVTextValue.getPageNumber());
                    String fxqxText = fxqxKVTextValue.getText();
                    logger.info("抽取的发行期限为：{}，页码为：{}",fxqxText,fxqxKVTextValue.getPageNumber());

                    if(StringUtils.isNotEmpty(qxrText) && StringUtils.isNotEmpty(fxqxText)){
                        Calendar qxrCalendar = c1002.dealDate(qxrText);

                        if(qxrCalendar!=null){
                            qxrComponentResult.setAnnotationFlag(false);
                            qxrComponentResult.setPromptMessage("已识别起息日：".concat(qxrText));

                            Map<String,String> releaseDateMap=c1002.getReleaseDate(fxqxText);

                            String releaseDateFlag=releaseDateMap.get("flag");

                            if(!releaseDateFlag.equals("false")){
                                if(StringUtils.isNotEmpty(releaseDateMap.get("value"))){
                                    if(releaseDateFlag.equals("year")){
                                        logger.info("发行期限：单位：年，值：{}",releaseDateMap.get("value"));
                                        qxrCalendar.add(Calendar.YEAR,Integer.parseInt(releaseDateMap.get("value")));
                                    }else if(releaseDateFlag.equals("day")){
                                        logger.info("发行期限：单位：天，值：{}",releaseDateMap.get("value"));
                                        qxrCalendar.add(Calendar.DATE,Integer.parseInt(releaseDateMap.get("value")));
                                    }
                                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

                                    String theoreticalValue = simpleDateFormat.format(qxrCalendar.getTime());
                                    logger.info("理论起息日为：{}",theoreticalValue);

                                    fxqxComponentResult.setAnnotationFlag(false);
                                    fxqxComponentResult.setPromptMessage("已识别发行期限：".concat(fxqxText));

                                    if(fxrKVTextValue!=null){
                                        componentResult = c1002.setTextPosition(fxrKVTextKey,componentResult);

                                        String fxrText = fxrKVTextValue.getText();
                                        logger.info("付息日：{}",fxrText);

                                        if(StringUtils.isNotEmpty(fxrText)){
                                            Calendar fxrCalendar = null;

                                            if(fxrText.contains("每年")){
                                                fxrCalendar = dealDate(fxrText,true);
                                            }else{
                                                fxrCalendar = dealDate(fxrText,false);
                                            }

                                            if(fxrCalendar!=null){
                                                if(fxrText.contains("每年")){
                                                    simpleDateFormat = new SimpleDateFormat("MM-dd");
                                                    Calendar qxrTempCalendar = c1002.dealDate(qxrText);
                                                    qxrTempCalendar.add(Calendar.YEAR,1);
                                                    theoreticalValue = new SimpleDateFormat("yyyy-MM-dd").format(qxrTempCalendar.getTime());
                                                }

                                                String qxrTemp=simpleDateFormat.format(qxrCalendar.getTime());
                                                logger.info("理论付息日:{}",qxrTemp);
                                                String fxrTemp=simpleDateFormat.format(fxrCalendar.getTime());
                                                logger.info("付息日:{}",fxrTemp);

                                                if(qxrTemp.equals(fxrTemp)){
                                                    logger.info("与理论付息日对比一致");
                                                    componentResult.setPromptMessage("第三章付息日与系统计算的理论付息日对比一致，系统计算的理论付息日为：".concat(theoreticalValue));
                                                    componentResult.setAnnotationFlag(false);
                                                }else{
                                                    logger.info("与理论付息日对比不一致");
                                                    componentResult.setPromptMessage("付息日与系统计算的理论付息日对比不一致，请核对付息日，系统计算的理论付息日为：".concat(theoreticalValue));
                                                    componentResult.setExist("02");
                                                    componentResult.setAnnotationFlag(false);

                                                    qxrComponentResult.setExist("02");
                                                    fxqxComponentResult.setExist("02");
                                                }
                                            }else{
                                                componentResult.setPromptMessage("未识别付息日，建议人工核对，系统计算的理论付息日为：".concat(theoreticalValue));
                                                componentResult.setAnnotationFlag(false);
                                            }
                                        }else{
                                            componentResult.setPromptMessage("未识别付息日，建议人工核对，系统计算的理论付息日为：".concat(theoreticalValue));
                                            componentResult.setAnnotationFlag(false);
                                        }
                                    }else{
                                        componentResult.setPromptMessage("未识别付息日，建议人工核对，系统计算的理论付息日为：".concat(theoreticalValue));
                                        componentResult.setAnnotationFlag(false);
                                    }
                                }else{
                                    fxqxComponentResult.setPromptMessage("未识别发行期限,无法计算理论付息日，建议人工核对");
                                    fxqxComponentResult.setAnnotationFlag(false);
                                    componentResult.setPromptMessage("未识别发行期限，无法计算理论付息日，建议人工核对");
                                    if(fxrKVTextKey!=null){
                                        componentResult = c1002.setTextPosition(fxrKVTextKey,componentResult);
                                    }
                                }
                            }else{
                                fxqxComponentResult.setPromptMessage("未识别发行期限,无法计算理论付息日，建议人工核对");
                                fxqxComponentResult.setAnnotationFlag(false);
                                componentResult.setPromptMessage("未识别发行期限，无法计算理论付息日，建议人工核对");
                                if(fxrKVTextKey!=null){
                                    componentResult = c1002.setTextPosition(fxrKVTextKey,componentResult);
                                }
                            }

                        }else{
                            qxrComponentResult.setPromptMessage("起息日数据缺失：".concat(qxrText));
                            fxqxComponentResult.setPromptMessage("已识别发行期限：".concat(fxqxText));
                            componentResult.setPromptMessage("起息日数据缺失，无法计算理论付息日");
                            if(fxrKVTextKey!=null){
                                componentResult = c1002.setTextPosition(fxrKVTextKey,componentResult);
                            }
                        }

                        componentResults.add(qxrComponentResult);
                        componentResults.add(fxqxComponentResult);
                        componentResults.add(componentResult);
                    }else{
                        if(StringUtils.isNotEmpty(qxrText)){
                            Calendar qxrCalendar = c1002.dealDate(qxrText);
                            if(qxrCalendar!=null){
                                qxrComponentResult.setPromptMessage("已识别起息日：".concat(qxrText));
                            }else{
                                qxrComponentResult.setPromptMessage("起息日数据缺失：".concat(qxrText));
                            }
                            qxrComponentResult.setAnnotationFlag(false);
                        }else{
                            qxrComponentResult.setPromptMessage("未识别起息日，无法计算，建议人工核对");
                            if(qxrComponentResult.getPageNum()==0){
                                if(chapterModel!=null){
                                    qxrComponentResult.setPageNum(chapterModel.getStartPage());
                                }
                            }

                            componentResult.setPromptMessage("未识别起息日");
                            if(fxrKVTextKey!=null){
                                componentResult = c1002.setTextPosition(fxrKVTextKey,componentResult);
                            }
                        }

                        if(StringUtils.isNotEmpty(fxqxText)){
                            fxqxComponentResult.setPromptMessage("已识别发行期限：".concat(fxqxText));
                            fxqxComponentResult.setAnnotationFlag(false);
                        }else{
                            fxqxComponentResult.setPromptMessage("未识别发行期限");
                            if(fxqxComponentResult.getPageNum()==0){
                                if(chapterModel!=null){
                                    fxqxComponentResult.setPageNum(chapterModel.getStartPage());
                                }
                            }

                            componentResult.setPromptMessage("未识别发行期限，无法计算，建议人工核对");
                            if(fxrKVTextKey!=null){
                                componentResult = c1002.setTextPosition(fxrKVTextKey,componentResult);
                            }
                        }

                        componentResults.add(qxrComponentResult);
                        componentResults.add(fxqxComponentResult);
                        componentResults.add(componentResult);
                        return componentResults;
                    }

                }else{
                    if(qxrKVTextValue!=null){
                        qxrComponentResult.setPageNum(qxrKVTextKey.getPageNumber());
                        if(StringUtils.isNotEmpty(qxrKVTextValue.getText())){
                            Calendar qxrCalendar = c1002.dealDate(qxrKVTextValue.getText());
                            if(qxrCalendar!=null){
                                qxrComponentResult.setPromptMessage("已识别起息日：".concat(qxrKVTextValue.getText()));
                            }else{
                                qxrComponentResult.setPromptMessage("起息日数据缺失：".concat(qxrKVTextValue.getText()));
                            }

                        }else{
                            qxrComponentResult.setPromptMessage("已识别起息日");
                        }
                        qxrComponentResult.setAnnotationFlag(false);

                        if(qxrKVTextKey!=null){
                            qxrComponentResult=c1002.setTextPosition(qxrKVTextKey,qxrComponentResult);
                        }
                    }else{
                        qxrComponentResult.setPromptMessage("未识别起息日");

                        if(qxrKVTextKey!=null){
                            qxrComponentResult=c1002.setTextPosition(qxrKVTextKey,qxrComponentResult);
                        }

                        if(qxrComponentResult.getPageNum()==0){
                            if(chapterModel!=null){
                                qxrComponentResult.setPageNum(chapterModel.getStartPage());
                            }
                        }

                        componentResult.setPromptMessage("未识别起息日，无法计算，建议人工核对");
                        if(fxqxKVTextKey!=null){
                            componentResult = c1002.setTextPosition(fxqxKVTextKey,componentResult);
                        }
                    }

                    if(fxqxKVTextValue!=null){
                        fxqxComponentResult.setPageNum(fxqxComponentResult.getPageNum());
                        if(StringUtils.isNotEmpty(fxqxKVTextValue.getText())){
                            fxqxComponentResult.setPromptMessage("已识别发行期限：".concat(fxqxKVTextValue.getText()));
                        }else{
                            fxqxComponentResult.setPromptMessage("已识别发行期限");
                        }

                        fxqxComponentResult.setAnnotationFlag(false);

                        if(fxqxKVTextKey!=null){
                            fxqxComponentResult=c1002.setTextPosition(fxqxKVTextKey,fxqxComponentResult);
                        }
                    }else{
                        fxqxComponentResult.setPromptMessage("未识别发行期限");
                        if(chapterModel!=null){
                            fxqxComponentResult.setPageNum(chapterModel.getStartPage());
                        }

                        if(fxqxComponentResult.getPageNum()==0){
                            if(chapterModel!=null){
                                fxqxComponentResult.setPageNum(chapterModel.getStartPage());
                            }
                        }

                        componentResult.setPromptMessage("未识别发行期限，无法计算，建议人工核对");
                        if(fxqxKVTextKey!=null){
                            componentResult = c1002.setTextPosition(fxqxKVTextKey,componentResult);
                        }
                    }

                    componentResults.add(qxrComponentResult);
                    componentResults.add(fxqxComponentResult);
                    componentResults.add(componentResult);
                    return componentResults;
                }

            }else{
                componentResult.setPromptMessage("未识别".concat(getCatalogId()).concat("数据，建议人工核对"));
                componentResults.add(componentResult);
                return componentResults;
            }

        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }

        return componentResults;
    }
}
